package service;

import dao.MessageDAO;
import dao.MessageDAOImpl;
import entity.Message;
import entity.User;
import java.util.List;

public class MessageService {
    private MessageDAO messageDAO;
    private UserService userService;  // 依赖用户服务查询用户名

    public MessageService() {
        this.messageDAO = new MessageDAOImpl();
        this.userService = new UserService();
    }

    // 发送消息（验证接收者是否存在）
    public boolean sendMessage(int senderId, int receiverId, String content) {
        // 验证接收者是否存在
        User receiver = userService.getUserById(receiverId);
        if (receiver == null) {
            System.out.println("接收者不存在！");
            return false;
        }
        // 发送消息
        Message message = new Message(senderId, receiverId, content);
        return messageDAO.sendMessage(message);
    }

    // 获取与指定用户的聊天记录，并标记未读消息为已读
    public List<Message> getChatHistory(int currentUserId, int targetUserId) {
        List<Message> history = messageDAO.getChatHistory(currentUserId, targetUserId);
        // 标记当前用户收到的未读消息为已读
        for (Message msg : history) {
            if (msg.getReceiverId() == currentUserId && !msg.isRead()) {
                messageDAO.markAsRead(msg.getMessageId());
            }
        }
        return history;
    }

    // 查看当前用户的未读消息总数
    public int getUnreadCount(int userId) {
        return messageDAO.getUnreadCount(userId);
    }
}